const { Service } = require('egg');
const myDate = require('../utils/myDate');

class BankService extends Service {
  async addTag(tagInfo) {
    const isExit = await this.app.mysql.get('tag', { name: tagInfo.name });
    if (isExit) {
      return {
        state: false,
        msg: '标签已存在',
      };
    }
    tagInfo.create_time = myDate.getNowDate();
    tagInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    tagInfo.create_by = userInfo.id;
    tagInfo.update_by = userInfo.id;
    const result = await this.app.mysql.insert('tag', tagInfo);
    if (result) {
      return {
        state: true,
        msg: '添加成功',
      };
    }
    return {
      state: false,
      msg: '添加失败',
    };
  }

  async updateTag(tagInfo) {
    tagInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    tagInfo.update_by = userInfo.id;
    const res = await this.app.mysql.update('tag', {
      id: tagInfo.id,
      name: tagInfo.name,
      color: tagInfo.color,
      update_time: tagInfo.update_time,
      update_by: tagInfo.update_by,
    });
    if (res) {
      return {
        state: true,
        msg: '修改成功',
      };
    }
    return {
      state: false,
      msg: '修改失败',
    };
  }

  async getTag(id) {
    const res = await this.app.mysql.get('tag', { id });
    if (res) {
      return res;
    }
    return false;
  }
  async getTags(pageNum, pageSize, name) {
    if (!pageNum) {
      pageNum = 1;
    }
    if (!pageSize) {
      pageSize = 10;
    }
    let where = '';
    if (name) {
      where = `WHERE name LIKE '%${name}%'`;
    }
    const total = await this.app.mysql.count('tag');
    const res = await this.app.mysql.query(`SELECT * FROM tag ${where} LIMIT ?, ?`, [ (pageNum - 1) * pageSize, pageSize ]);
    if (res) {
      return {
        tags: res,
        total,
      };
    }
    return false;
  }

  async delTags(ids) {
    await this.app.mysql.query(
      `DELETE FROM ques_tag WHERE tag_id in (${ids.join(',')})`
    );
    const res = await this.app.mysql.query(
      `delete from tag where id in (${ids.join(',')})`
    );
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async addQuesType(quesType) {
    quesType.create_time = myDate.getNowDate();
    quesType.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    quesType.create_by = userInfo.id;
    quesType.update_by = userInfo.id;
    quesType.data = JSON.stringify(quesType.data);
    const res = await this.app.mysql.insert('ques_type', quesType);
    if (res) {
      return true;
    }
    return false;
  }
  async updateQuesType(quesType) {
    const isExist = await this.app.mysql.get('ques_type', { id: quesType.id });
    if (!isExist) {
      return false;
    }
    quesType.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    quesType.update_by = userInfo.id;
    quesType.data = JSON.stringify(quesType.data);
    const res = await this.app.mysql.update('ques_type', {
      id: quesType.id,
      name: quesType.name,
      data: quesType.data,
      update_time: quesType.update_time,
      update_by: quesType.update_by,
    });
    return res.affectedRows > 0;
  }
  async getQuseType(id) {
    const res = await this.app.mysql.get('ques_type', { id });
    if (res) {
      return res;
    }
    return false;
  }

  async getQuseTypes(pageNum, pageSize, name) {
    if (!pageNum) {
      pageNum = 1;
    }
    if (!pageSize) {
      pageSize = 10;
    }
    let where = '';
    if (name) {
      where = `WHERE name LIKE '%${name}%'`;
    }
    const total = await this.app.mysql.count('ques_type');
    const res = await this.app.mysql.query(`SELECT * FROM ques_type ${where} LIMIT ?, ?`, [ (pageNum - 1) * pageSize, pageSize ]);
    if (res) {
      return {
        quesTypes: res,
        total,
      };
    }
    return false;
  }

  async delQuesType(ids) {
    const usedCount = await this.app.mysql.query(`SELECT COUNT(*) AS count FROM ques WHERE type IN (${ids.join(',')})`);
    if (usedCount[0].count > 0) {
      return {
        state: false,
        msg: '删除失败，请先删除该分类下的题目',
      };
    }
    const res = await this.app.mysql.query(
      `delete from ques_type where id in (${ids.join(',')})`
    );
    if (res.affectedRows > 0) {
      return {
        state: true,
        msg: '删除成功',
      };
    }
    return {
      state: false,
      msg: '删除失败',
    };
  }

  async addQues(quesInfo) {
    const quesType = await this.app.mysql.get('ques_type', { id: quesInfo.type });
    if (!quesType) {
      return {
        state: false,
        msg: '题型不存在',
      };
    }
    quesInfo.type_name = quesType.name;
    const quesData = quesInfo.data;
    const quesTypeDate = JSON.parse(quesType.data);
    for (let i = 0; i < quesTypeDate.length; i++) {
      if (quesTypeDate[i].type !== quesData[i].type) {
        return {
          state: false,
          msg: '题型与题目类型不匹配',
        };
      }
    }
    quesInfo.create_time = myDate.getNowDate();
    quesInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    quesInfo.create_by = userInfo.id;
    quesInfo.update_by = userInfo.id;
    quesInfo.data = JSON.stringify(quesInfo.data);
    quesInfo.answer = JSON.stringify(quesInfo.answer);
    const tagIds = quesInfo.tagIds;
    const result = await this.app.mysql.insert('ques', {
      data: quesInfo.data,
      title: quesInfo.title,
      type_name: quesInfo.type_name,
      type: quesInfo.type,
      answer: quesInfo.answer,
      create_by: quesInfo.create_by,
      update_by: quesInfo.update_by,
      create_time: quesInfo.create_time,
      update_time: quesInfo.update_time,
    });
    if (result) {
      if (tagIds) {
        for (let i = 0; i < tagIds.length; i++) {
          const element = tagIds[i];
          await this.app.mysql.insert('ques_tag', {
            tag_id: element,
            ques_id: result.insertId,
          });
        }
      }
      return {
        state: true,
        msg: '添加成功',
      };
    }
    return {
      state: false,
      msg: '添加失败',
    };
  }

  async delQues(ids) {
    const res = await this.app.mysql.query(
      `delete from ques where id in (${ids.join(',')})`
    );
    await this.app.mysql.query(
      `delete from ques_tag where ques_id in (${ids.join(',')})`
    );
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async updateQues(quesInfo) {
    const quesType = await this.app.mysql.get('ques_type', { id: quesInfo.type });
    if (!quesType) {
      return {
        state: false,
        msg: '题型不存在',
      };
    }
    const isExit = await this.app.mysql.get('ques', { id: quesInfo.id });
    if (!isExit) {
      return {
        state: false,
        msg: '题目不存在',
      };
    }
    quesInfo.type_name = quesType.name;
    const quesData = quesInfo.data;
    const quesTypeDate = JSON.parse(quesType.data);
    for (let i = 0; i < quesTypeDate.length; i++) {
      if (quesTypeDate[i].type !== quesData[i].type) {
        return {
          state: false,
          msg: '题型与题目类型不匹配',
        };
      }
    }
    quesInfo.create_time = isExit.create_time;
    quesInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    quesInfo.update_by = userInfo.id;
    quesInfo.create_by = isExit.create_time;
    quesInfo.data = JSON.stringify(quesInfo.data);
    quesInfo.answer = JSON.stringify(quesInfo.answer);
    const result = await this.app.mysql.update('ques', {
      id: quesInfo.id,
      data: quesInfo.data,
      title: quesInfo.title,
      type_name: quesInfo.type_name,
      type: quesInfo.type,
      answer: quesInfo.answer,
      create_by: quesInfo.create_by,
      update_by: quesInfo.update_by,
      create_time: quesInfo.create_time,
      update_time: quesInfo.update_time,
    });
    await this.app.mysql.delete('ques_tag', { ques_id: quesInfo.id });
    if (quesInfo.tagIds && quesInfo.tagIds.length > 0) {
      for (const tagId of quesInfo.tagIds) {
        await this.app.mysql.insert('ques_tag', {
          ques_id: quesInfo.id,
          tag_id: tagId,
        });
      }
    }
    if (result) {
      return {
        state: true,
        msg: '更新成功',
      };
    }
    return {
      state: false,
      msg: '更新失败',
    };
  }

  async getQues(id) {
    const res = await this.app.mysql.get('ques', { id });
    if (res) {
      return res;
    }
    return false;
  }

  async getQuess(pageNum, pageSize, title) {
    if (!pageNum) {
      pageNum = 1;
    }
    if (!pageSize) {
      pageSize = 10;
    }
    let orderBy = '';
    if (title) {
      // 添加排序规则：完全匹配的排在最前面，然后是按匹配度排序
      orderBy = `
        ORDER BY 
          CASE 
            WHEN q.title = '${title}' THEN 1
            WHEN q.title LIKE '${title}%' THEN 2 
            WHEN q.title LIKE '%${title}%' THEN 3
            ELSE 4
          END,
          LENGTH(q.title) ASC
      `;
    } else {
      orderBy = '';
    }
    const total = await this.app.mysql.count('ques');
    const sql = `
      SELECT 
          q.*,
          qt.name AS type_name,
          GROUP_CONCAT(DISTINCT t.id) AS tagIds,
          GROUP_CONCAT(DISTINCT t.name) AS tagNames
       FROM 
          ques q
       LEFT JOIN 
          ques_type qt ON q.type = qt.id
       LEFT JOIN 
          ques_tag qtg ON q.id = qtg.ques_id
       LEFT JOIN 
          tag t ON qtg.tag_id = t.id
       GROUP BY 
          q.id
       ${orderBy || ''}
       LIMIT ?, ?`;
    const res = await this.app.mysql.query(sql, [ (pageNum - 1) * pageSize, pageSize ]);
    if (res) {
      return {
        ques: res,
        total,
      };
    }
    return false;
  }
}

module.exports = BankService;

